<script setup lang="ts">
import { computed, reactive, ref, watch } from 'vue';
import { useFormRules, useNaiveForm } from '@/hooks/common/form';
import { addFillData, updateFillData, fetchFillTemplateList } from '@/service/api';
import { $t } from '@/locales';

defineOptions({
  name: 'DataOperateDrawer'
});

interface Props {
  operateType: 'add' | 'edit';
  rowData?: Api.Dataplatform.FillData | null;
}

const props = defineProps<Props>();

interface Emits {
  (e: 'success'): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', {
  default: false
});

const { formRef, validate, restoreValidation } = useNaiveForm();
const { defaultRequiredRule } = useFormRules();

const title = computed(() => {
  const titles: Record<'add' | 'edit', string> = {
    add: $t('page.dataplatform.fill.addData'),
    edit: $t('page.dataplatform.fill.editData')
  };
  return titles[props.operateType];
});

type Model = Pick<Api.Dataplatform.FillDataEdit, 'templateId' | 'dataContent' | 'remark'>;

const model: Model = reactive(createDefaultModel());
const templateOptions = ref<Array<{ label: string; value: number }>>([]);

function createDefaultModel(): Model {
  return {
    templateId: undefined as any,
    dataContent: '',
    remark: ''
  };
}

type RuleKey = Extract<keyof Model, 'templateId' | 'dataContent'>;

const rules: Record<RuleKey, App.Global.FormRule> = {
  templateId: defaultRequiredRule,
  dataContent: defaultRequiredRule
};

async function loadTemplates() {
  const { data, error } = await fetchFillTemplateList({ pageNum: 1, pageSize: 100, status: 1 });
  if (!error && data) {
    templateOptions.value = data.rows.map(item => ({
      label: item.name,
      value: item.id
    }));
  }
}

function handleInitModel() {
  Object.assign(model, createDefaultModel());

  if (props.operateType === 'edit' && props.rowData) {
    Object.assign(model, {
      templateId: props.rowData.templateId,
      dataContent: props.rowData.dataContent,
      remark: props.rowData.remark
    });
  }
}

function closeDrawer() {
  visible.value = false;
}

async function handleSubmit() {
  await validate();

  const api = props.operateType === 'add' ? addFillData : updateFillData;
  const data: Api.Dataplatform.FillDataEdit = {
    ...model
  };

  if (props.operateType === 'edit' && props.rowData) {
    data.id = props.rowData.id;
  }

  const { error } = await api(data);
  if (!error) {
    window.$message?.success(
      props.operateType === 'add' ? $t('common.addSuccess') : $t('common.updateSuccess')
    );
    closeDrawer();
    emit('success');
  }
}

watch(visible, () => {
  if (visible.value) {
    handleInitModel();
    restoreValidation();
    loadTemplates();
  }
});
</script>

<template>
  <NDrawer v-model:show="visible" display-directive="show" :width="640">
    <NDrawerContent :title="title" :native-scrollbar="false" closable>
      <NForm ref="formRef" :model="model" :rules="rules" label-placement="left" :label-width="120">
        <NFormItem :label="$t('page.dataplatform.fill.template')" path="templateId">
          <NSelect
            v-model:value="model.templateId"
            :placeholder="$t('page.dataplatform.fill.selectTemplate')"
            :options="templateOptions"
            :disabled="operateType === 'edit'"
          />
        </NFormItem>
        <NFormItem :label="$t('page.dataplatform.fill.dataContent')" path="dataContent">
          <NInput
            v-model:value="model.dataContent"
            type="textarea"
            :placeholder="$t('page.dataplatform.fill.dataContentPlaceholder')"
            :rows="15"
          />
        </NFormItem>
        <NFormItem :label="$t('page.dataplatform.common.remark')" path="remark">
          <NInput
            v-model:value="model.remark"
            type="textarea"
            :placeholder="$t('page.dataplatform.common.remarkPlaceholder')"
            :rows="2"
          />
        </NFormItem>
      </NForm>
      <template #footer>
        <NSpace justify="end">
          <NButton @click="closeDrawer">{{ $t('common.cancel') }}</NButton>
          <NButton type="primary" @click="handleSubmit">{{ $t('common.confirm') }}</NButton>
        </NSpace>
      </template>
    </NDrawerContent>
  </NDrawer>
</template>

<style scoped></style>
